//
//  VC_Home.m
//  yjw-winner
//
//  Created by Kae on 2018/9/3.
//  Copyright © 2018年 Shanghai decade financial information service co., LTD. All rights reserved.
//

#import "VC_Home.h"
#import "Cell_Home.h"
#import "VC_Course.h"
#import "VC_Audio.h"
#import "VC_JoinWinner.h"
#import "HomeSectionViewCourseNotice.h"
#import "HomeSectionTrendLabel.h"
#import "VC_CourseList.h"
#import "VC_SettingIntroduce.h"
#import "VC_AllTagCourse.h"


static NSString *identifier = @"home_cell_identifier";
@interface VC_Home () <UITableViewDelegate, UITableViewDataSource>{
    
    UITableView *_tableView;
}

@property (nonatomic, strong) NSArray *dataArray;
@property (nonatomic, strong) UIView *headView;
@property (nonatomic, strong) UILabel *userWelcomeLabel;

@property (nonatomic, strong) HomeSectionViewCourseNotice *noticeHeadView;
@property (nonatomic, strong) HomeSectionTrendLabel *trendLabelHeadView;
@end

@implementation VC_Home
- (void)awakeFromNib {
    [super awakeFromNib];
    [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]} forState:UIControlStateNormal];
    [[UIBarButtonItem appearance] setTitlePositionAdjustment:UIOffsetMake(-100, 0) forBarMetrics:UIBarMetricsDefault];
}
- (UIView *)headView {
    if (!_headView) {
        _headView = [[UIView alloc] init];
        _headView.backgroundColor = [UIColor whiteColor];
        _headView.bounds = CGRectMake(0, 0, self.view.bounds.size.width, 150);
        
        
        UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _headView.bounds.size.width, 110)];
        topView.backgroundColor = MJRefreshColor(17, 25, 31);
        [_headView addSubview:topView];
        
        UILabel *l = [[UILabel alloc] initWithFrame:CGRectMake(0, topView.bounds.size.height * 0.5 - 20, topView.mj_w, 20)];
        l.text = @"欢迎加入赢家大学商学院";
        l.font = [UIFont systemFontOfSize:19];
        l.textAlignment = NSTextAlignmentCenter;
        l.textColor = [UIColor whiteColor];
        [topView addSubview:l];
        
        UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom];
        b.frame = CGRectMake((topView.mj_w - 75) * 0.5, topView.mj_h * 0.5 + 4, 75, 25);
        b.layer.masksToBounds = YES;
        b.layer.cornerRadius = 2.0f;
        [b setTitle:@"查看详情" forState:UIControlStateNormal];
        b.titleLabel.font = [UIFont systemFontOfSize:12];
        [b setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        b.backgroundColor = MJRefreshColor(210, 169, 115);
        [b addTarget:self action:@selector(homeWinnerDetailButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [topView addSubview:b];
        
        self.userWelcomeLabel.frame =  CGRectMake(10, topView.mj_h, _headView.mj_w - 115, _headView.mj_h - topView.mj_h);
        [_headView addSubview:self.userWelcomeLabel];
        
        UIButton *b_join = [UIButton buttonWithType:UIButtonTypeCustom];
        b_join.frame = CGRectMake(_headView.mj_w - 10 - 80, topView.mj_h + (_headView.mj_h - topView.mj_h - 25) * 0.5, 80, 25);
        b_join.layer.masksToBounds = YES;
        b_join.layer.cornerRadius = 12.5;
        b_join.titleLabel.font = [UIFont systemFontOfSize:12];
        b_join.backgroundColor = MJRefreshColor(212, 171, 117);
        [b_join setTitle:@"加入商学院" forState:UIControlStateNormal];
        [b_join setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [b_join addTarget:self action:@selector(homeJoinButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [_headView addSubview:b_join];
    }
    return _headView;
}
- (UILabel *)userWelcomeLabel {
    if (!_userWelcomeLabel) {
        _userWelcomeLabel = [[UILabel alloc] init];
        _userWelcomeLabel.numberOfLines = 0;
        _userWelcomeLabel.font = [UIFont systemFontOfSize:12];
        _userWelcomeLabel.textColor = [UIColor blackColor];
        _userWelcomeLabel.text = @"小草儿你好!欢迎来到赢家大学,这里有免费的课程,赶快学习吧!";
    }
    return _userWelcomeLabel;
}

- (HomeSectionViewCourseNotice *)noticeHeadView {
    if (!_noticeHeadView) {
        _noticeHeadView = [HomeSectionViewCourseNotice headView];
        _noticeHeadView.frame = CGRectMake(0, 0, self.view.mj_w, 130);
    }
    return _noticeHeadView;
}
- (HomeSectionTrendLabel *)trendLabelHeadView {
    if (!_trendLabelHeadView) {
        _trendLabelHeadView = [HomeSectionTrendLabel headView];
        _trendLabelHeadView.frame = CGRectMake(0, 0, self.view.mj_w, 190);
    }
    return _trendLabelHeadView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.showsHorizontalScrollIndicator = NO;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = MJRefreshColor(242, 242, 242);
    _tableView.tableFooterView = [UIView new];
    _tableView.tableHeaderView = self.headView;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    __weak typeof(self) weakself = self;
    [self loadData];
    [self.noticeHeadView refreshWithModel:nil CallBackBlock:^{
        typeof(weakself) strongself = weakself;
        [strongself homeCourseListCellCallBack:nil];
    }];
}


#pragma mark --mark UITableViewDelegate UITableViewDataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    Model_Course *model = self.dataArray[indexPath.section][indexPath.row];
    Cell_Home *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[Cell_Home alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    if (indexPath.section > 0) {
        cell.tipLabel.text = @"";
    }else {
        if (indexPath.row == 0) {
            cell.tipLabel.text = @"免费体验";
        }else {
            cell.tipLabel.text = @"最新课程";
        }
    }
    __weak typeof(self) weakself = self;
    [cell refreshWithModel:model CallBackBlock:^(Model_Course *model, CellHomeButtonType type) {
        typeof(weakself) strongself = weakself;
        [strongself homeCellCallBack:model CellHomeButtonType:type];
    }];
    return cell;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *arr = self.dataArray[section];
    return arr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 270.0f;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    @autoreleasepool {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 10.0f)];
        return view;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    @autoreleasepool {
        if (section == 1) {
            // 课程预告
            return self.noticeHeadView;
        }else if (section == 2) {
            // 热门标签
            __weak typeof(self) weakself = self;
            [self.trendLabelHeadView refreshWith:nil CallBackBlock:^(NSString *labelText) {
                typeof(weakself) strongself = weakself;
                [strongself homeCourseListFilterWithLabel:labelText];
            }];
            return self.trendLabelHeadView;
        }else {
            UIView *view = [UIView new];
            return view;
        }
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10.0f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        return self.noticeHeadView.mj_h;
    }else if (section == 2) {
        return self.trendLabelHeadView.mj_h;
    }else {
        return CGFLOAT_MIN;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    Model_Course *model = self.dataArray[indexPath.section][indexPath.row];
    [self showCourseDetailWithModel:model];
}


#pragma mark --mark 处理数据

- (void)loadData {
    NSMutableArray *mArr = [NSMutableArray array];
    dispatch_queue_t queue = dispatch_queue_create("myqueue", DISPATCH_QUEUE_SERIAL);
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, queue, ^{
        // 对列 1 获取免费体验课程
        Model_Course *model0 = [[[CourseManager manager] filterCourseWithLecturerId:@"1"] firstObject];
        // 获取最新课程
        Model_Course *model1 = [[[CourseManager manager] filterCourseWithLecturerId:@"2"] lastObject];
        [mArr addObject:@[model0, model1]];
    });
    dispatch_group_async(group, queue, ^{
       // 队列 2 获取课程预告
        Model_Course *model0 = [[[CourseManager manager] filterCourseWithLecturerId:@"1"] lastObject];
        Model_Course *model1 = [[[CourseManager manager] filterCourseWithLecturerId:@"2"] lastObject];
        [mArr addObject:@[model0, model1]];
    });
    dispatch_group_async(group, queue, ^{
       // 队列 2 获取标签数据
        NSArray *arr = [[CourseManager manager] filterCourseWithCourseLabel:@"股票"];
        [mArr addObject:arr];
    });
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        // 刷新数据
        self.dataArray = [NSArray arrayWithArray:mArr];
        [_tableView reloadData];
    });
    
}

#pragma mark --mark EVENT

- (void)homeWinnerDetailButtonClick:(UIButton *)sender {
    VC_SettingIntroduce *vc = [[VC_SettingIntroduce alloc] initWithNibName:NSStringFromClass([VC_SettingIntroduce class]) bundle:[NSBundle mainBundle]];
    vc.hidesBottomBarWhenPushed = YES;
    vc.title = @"赢家大学";
    [self.navigationController pushViewController:vc animated:YES];
}

/**
 加入赢家大学

 @param sender sender
 */
- (void)homeJoinButtonClick:(UIButton *)sender {
    VC_JoinWinner *vc = [[VC_JoinWinner alloc] initWithNibName:NSStringFromClass([VC_JoinWinner class]) bundle:[NSBundle mainBundle]];
    vc.title = @"安全支付";
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}




#pragma mark --mark 业务逻辑

/**
 筛选标签

 @param text text
 */
- (void)homeCourseListFilterWithLabel:(NSString *)text {
    if (!text) {
        VC_AllTagCourse *vc = [[VC_AllTagCourse alloc] init];
        vc.view.backgroundColor = [UIColor whiteColor];
        vc.title = @"全部标签";
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    NSArray *arr = [[CourseManager manager] filterCourseWithCourseLabel:text];
    if (arr.count) {
        NSMutableArray *mArr = [NSMutableArray arrayWithArray:self.dataArray];
        [mArr removeObjectAtIndex:mArr.count - 1];
        [mArr addObject:arr];
        self.dataArray = [NSArray arrayWithArray:mArr];
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:2];
        [_tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
    }else {
        [MBProgressHUD showSuccess:@"没有更多课程了～"];
    }
}


- (void)homeCourseListCellCallBack:(id)model {
    VC_CourseList *vc = [[VC_CourseList alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    vc.title = @"商学院课程表";
    [self.navigationController pushViewController:vc animated:YES];
}

/**
 点击cell按钮回调

 @param model model
 @param type type
 */
- (void)homeCellCallBack:(Model_Course *)model CellHomeButtonType:(CellHomeButtonType)type {
    switch (type) {
        case CellHomeButtonTypeAudio: {
            // 播放音频
            [self showAudioDetailWithModel:model];
            break;
        }
        case CellHomeButtonTypeVedio: {
            // 播放视频
            [self showCourseDetailWithModel:model];
            break;
        }
        default:
            break;
    }
}

/**
 查看课程详情

 @param model model
 */
- (void)showCourseDetailWithModel:(Model_Course *)model {
    VC_Course *vc = [[VC_Course alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    vc.model = model;
    [self.navigationController pushViewController:vc animated:YES];
}

/**
 查看音频详情

 @param model model
 */
- (void)showAudioDetailWithModel:(Model_Course *)model {
    VC_Audio *vc = [[VC_Audio alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    vc.model = model;
    [self.navigationController pushViewController:vc animated:YES];
}

@end
